package io.cloud.tec.jdk.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintThread {

    private Lock lock = new ReentrantLock();
    private int flag = 1;  // 控制执行哪个线程

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();


    public void printA() {

        lock.lock();

        try {
            while (flag != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 1");
            flag = 2;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printB() {
        lock.lock();

        try {
            while (flag != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 2");
            flag = 3;
            condition2.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void printC() {
        lock.lock();

        try {
            while (flag != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + " : 3");
            flag = 1;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class Main {
    // 问题在哪里？为什么还会执行几次循环，才卡住？
    public static void main(String[] args) {
        PrintThread printThread = new PrintThread();
        // 10个相同名称的线程，在同一个condition上互相signal，加上flag来实现的
        for (int i = 0; i < 10; i++) {
            new Thread(() -> printThread.printA(), "A").start();

            new Thread(() -> printThread.printB(), "B").start();

            new Thread(() -> printThread.printC(), "C").start();
        }
    }
}